package protocol

import (
	"fmt"
	"github.com/ethereum/go-ethereum/rlp"
)

const (
	Transaction            = 0x00
	TransactionCommit      = 0x01
	TransactionSuccess     = 0x02
	TransactionFail        = 0x03
	NewContendBlock        = 0x04
	NewTransactionBlock    = 0x05
	RegisterAccount        = 0x06
	RegisterAccountSuccess = 0x07
	RegisterAccountFail    = 0x08
	GetContendChainNo      = 0x09
	ContendChainNo         = 0x0A
	GetTransactionChainNo  = 0x0B
	TransactionChainNo     = 0x0C
	SyncContendChain       = 0x0D
	SyncTransactionChain   = 0x0E
	DelayedTransaction     = 0x0F
	InstallmentTransaction = 0x10
	ContendChain           = 0x11
	TransactionChain       = 0x12
	GetServerIP            = 0x13
	ServerIP               = 0x14
	GetAccountNo           = 0x15
	AccountNo              = 0x16
	SyncAccount            = 0x17
	Account                = 0x18
)

type Message struct {
	Code    uint64
	Size    uint64
	Payload []byte
	Source  string
}

func NewMessage(code uint64, val interface{}) *Message {
	if val == nil {
		val = ""
	}
	payload, err := rlp.EncodeToBytes(val)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return &Message{
		code,
		uint64(len(payload)),
		payload,
		"",
	}
}

func (msg Message) EncodeMessage() []byte {
	fmt.Println("进行消息编码")
	a, err := rlp.EncodeToBytes(msg)
	if err != nil {
		fmt.Println("EncodeMessage Error", err)
		return nil
	}
	fmt.Println(a)
	return a
}

func DecodeMessage(payload []byte) *Message {
	msg := &Message{}
	err := rlp.DecodeBytes(payload, msg)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return msg
}
